#!/bin/sh /etc/rc.common
# Copyright (C) 2023 Bruce Chen <a805899926@gmail.com>
#

START=25
STOP=89

USE_PROCD=1
PROG=/usr/bin/AdGuardHome

section_enabled() {
  config_get_bool enabled "$1" 'enabled' 0
  [ $enabled -gt 0 ]
}

start_instance() {
  local name="$1"

  section_enabled "$name" || {
    return 1
  }

  config_get port $name port
  [ -z "$port" ] && { 
    return 1 
  }

  [ ! -d "/var/run" ] && mkdir -p "/var/run"
  
  local pid_file=/var/run/adguardhome.$name.pid
  local log_file=/var/log/adguardhome.$name.log
  echo '' > $log_file

  config_get_bool debug "$name" debug 0

  local global_workdir
  config_get global_workdir 'global' workdir
  
  local config=/etc/adguardhome/$name.yaml
  local workdir=$global_workdir/$name

  [ -d "$workdir" ] || mkdir -m 0755 -p "$workdir"

  procd_open_instance "$name"
  procd_set_param command "$PROG" --pidfile $pid_file -l $log_file -c $config -w $workdir -p $port --no-check-update

  [ "$debug" -eq 1 ] && procd_append_param command --verbose

  procd_set_param respawn
  procd_close_instance
}

start_service() {
  local instance="$1"
  local instance_found=0
  
  config_cb() {
    local type="$1"
    local name="$2"
    if [ "$type" = "service" ]; then
      if [ -n "$instance" -a "$instance" = "$name" ]; then
        instance_found=1
      fi
    fi
  }

  config_load "adguardhome"

  if [ -n "$instance" ]; then
    [ "$instance_found" -gt 0 ] || return
    start_instance "$instance"
  else
    config_foreach start_instance 'service'
  fi
}

service_triggers() {
  procd_add_reload_trigger adguardhome
}